import { withLoading } from 'utils/dva';
import services from 'services';
import model from '../../model';
import { pageConfig } from 'configs/constants';

const defaultConfig = {
  pagination: {
    ...pageConfig,
    total: 0
  },
  list: []
};
const initDetails = {
  company: {},
  role: {},
  user: {}
};

export default model.extend ({
  namespace: 'personalManage',
  state: {
    config: defaultConfig,
    user: [],
    details: initDetails,
    qrCodePicUrl: '',
    initDetails,
    search: {},
    loading: {
      list: false,
      add: false,
      del: false
    }
  },

  subscriptions: {
    setup({ dispatch, history }) {
      // 监听路由的变化，请求页面数据
      return history.listen(({ pathname }) => {
        let list = [];
        if (pathname === '/personal/personalManage') {
          dispatch({ type: 'getUserInfo', payload: { list } });
          dispatch({ type: 'bindQrCode' });
        }
      });
    }
  },

  effects: {
    * getUserInfo({ payload }, { call, update }) {
      const { data } =  yield call(withLoading(services.user.userProfile), { ...payload });
      yield update({ details: data });
    },
    * bindQrCode({ payload }, { call, update }) {
      const { data } =  yield call(withLoading(services.user.bindQrCode), { ...payload });
      yield update({ qrCodePicUrl: data.qrCodePicUrl || '' });
    }
  },

  reducers: {
    goPage(state, { payload }) {
      return {
        ...state,
        config: {
          ...state.config,
          pagination: {
            ...state.config.pagination,
            current: payload
          }
        }
      };
    },
    updateSearch(state, { payload: params }) {
      const { pn = 1 } = params;
      return {
        ...state,
        search: { ...state.search, ...params },
        config: {
          ...state.config,
          pagination: { ...state.config.pagination, current: pn }
        }
      };
    }
  }

});
